<template>
  <div class="user-page">
    <!-- 顶部信息栏 -->
    <div class="top-bar">
      <span class="welcome-text">欢迎您，{{ $store.state.userInfo.username || '未知用户' }}！</span>
      <button
          class="logout-btn"
          @click="handleLogout"
          :loading="isLoggingOut"
      >
        退出登录
      </button>
    </div>

    <!-- 页面标题和操作区 -->
    <div class="header-actions">
      <h2 class="page-title">用户管理系统</h2>
      <div class="action-buttons">
        <!-- 搜索框 -->
        <div class="search-box">
          <input
              type="text"
              v-model="searchKeyword"
              placeholder="请输入用户名/手机号/订单详情搜索..."
              @keyup.enter="handleSearch"
          >
          <button class="search-btn" @click="handleSearch">搜索</button>
          <button
              class="reset-btn"
              @click="resetSearch"
              v-if="searchKeyword"
          >
            重置
          </button>
        </div>
        <!-- 添加按钮 -->
        <button class="add-btn" @click="showAddDialog = true">
          <i class="el-icon-plus"></i> 添加用户
        </button>
      </div>
    </div>

    <!-- 1. 用户列表表格 -->
    <div class="section-title">用户基本信息</div>
    <div class="loading" v-if="isLoading">
      <div class="spinner"></div>
      <p>加载用户数据中...</p>
    </div>
    <table class="user-table" v-else>
      <thead>
      <tr>
        <th>用户ID</th>
        <th>用户名</th>
        <th>手机号</th>
        <th>性别</th>
        <th>账户余额</th>
        <th>创建时间</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <!-- 无数据时显示 -->
      <tr v-if="userList.length === 0">
        <td colspan="7" class="no-data">暂无用户数据</td>
      </tr>
      <!-- 循环渲染用户数据 -->
      <tr v-for="user in userList" :key="user.id" class="user-row">
        <td>{{ user.id }}</td>
        <td>{{ user.username }}</td>
        <td>{{ user.phone || '未填写' }}</td>
        <td>
          <span class="sex-tag" :class="user.sex === 1 ? 'male' : user.sex === 2 ? 'female' : 'unknown'">
            {{ user.sex === 1 ? '男' : user.sex === 2 ? '女' : '未知' }}
          </span>
        </td>
        <td>{{ (user.money || 0).toFixed(2) }} 元</td>
        <td>{{ formatTime(user.createTime) }}</td>
        <td class="operation-buttons">
          <button
              class="delete-btn"
              @click="handleDelete(user.id)"
              :disabled="isDeleting"
          >
            <i class="el-icon-delete"></i> 删除
          </button>
        </td>
      </tr>
      </tbody>
    </table>

    <!-- 用户列表分页 -->
    <div class="pagination" v-if="!isLoading && totalCount > 0">
      <button
          class="page-btn"
          :disabled="currentPage === 1"
          @click="changePage(currentPage - 1)"
      >
        上一页
      </button>
      <div class="page-navigation">
        <span class="page-info">
          第 {{ currentPage }} 页 / 共 {{ totalPage }} 页
        </span>
        <div class="page-jump">
          跳至
          <input
              type="number"
              v-model.number="jumpPage"
              min="1"
              :max="totalPage"
              @keyup.enter="handleJump"
          >
          页
          <button class="jump-btn" @click="handleJump">确定</button>
        </div>
      </div>
      <button
          class="page-btn"
          :disabled="currentPage === totalPage || userList.length === 0"
          @click="changePage(currentPage + 1)"
      >
        下一页
      </button>
      <div class="page-size">
        每页显示：
        <select
            v-model="pageSize"
            @change="handlePageSizeChange"
        >
          <option value="5">5条</option>
          <option value="10">10条</option>
          <option value="20">20条</option>
          <option value="50">50条</option>
        </select>
      </div>
    </div>

    <!-- 2. 用户订单关联表格 -->
    <div class="section-title">用户订单关联信息</div>
    <div class="loading" v-if="isOrderLoading">
      <div class="spinner"></div>
      <p>加载用户订单数据中...</p>
    </div>
    <table class="user-table" v-else>
      <thead>
      <tr>
        <th>用户ID</th>
        <th>用户名</th>
        <th>手机号</th>
        <th>性别</th>
        <th>订单数量</th>
        <th>订单详情</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <!-- 无数据时显示 -->
      <tr v-if="userOrderList.length === 0">
        <td colspan="7" class="no-data">暂无用户订单数据</td>
      </tr>
      <!-- 循环渲染订单数据 -->
      <tr v-for="user in userOrderList" :key="user.id">
        <td>{{ user.id }}</td>
        <td>{{ user.username }}</td>
        <td>{{ user.phone || '未填写' }}</td>
        <td>
          <span class="sex-tag" :class="user.sex === 1 ? 'male' : user.sex === 2 ? 'female' : 'unknown'">
            {{ user.sex === 1 ? '男' : user.sex === 2 ? '女' : '未知' }}
          </span>
        </td>
        <td>{{ user.orderList ? user.orderList.length : 0 }}</td>
        <td>
          <div v-if="user.orderList && user.orderList.length > 0">
            <div v-for="order in user.orderList" :key="order.oid" class="order-item">
              {{ order.detail }} - ¥{{ order.price ? order.price.toFixed(2) : '0.00' }}
            </div>
          </div>
          <span v-else class="no-order">无订单</span>
        </td>
        <td>
          <!-- 订单操作按钮 -->
        </td>
      </tr>
      </tbody>
    </table>

    <!-- 订单列表分页 -->
    <div class="pagination" v-if="!isOrderLoading && orderTotalCount > 0">
      <button
          class="page-btn"
          :disabled="currentPage === 1"
          @click="changePage(currentPage - 1)"
      >
        上一页
      </button>
      <div class="page-navigation">
        <span class="page-info">
          第 {{ currentPage }} 页 / 共 {{ orderTotalPage }} 页
        </span>
      </div>
      <button
          class="page-btn"
          :disabled="currentPage === orderTotalPage || userOrderList.length === 0"
          @click="changePage(currentPage + 1)"
      >
        下一页
      </button>
    </div>

    <!-- 添加用户弹窗 -->
    <el-dialog
        title="添加新用户"
        :visible.sync="showAddDialog"
        width="500px"
        :close-on-click-modal="false"
    >
      <el-form
          ref="addForm"
          :model="addForm"
          :rules="addFormRules"
          label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addForm.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="addForm.sex">
            <el-radio label="1">男</el-radio>
            <el-radio label="2">女</el-radio>
            <el-radio label="0">未知</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="账户余额" prop="money">
          <el-input
              v-model.number="addForm.money"
              placeholder="请输入账户余额"
              type="number"
              clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
              v-model="addForm.password"
              placeholder="请设置密码"
              type="password"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button
            type="primary"
            @click="handleAddUser"
            :loading="isAdding"
        >
          确认添加
        </el-button>
      </div>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog
        title="确认删除"
        :visible.sync="showDeleteDialog"
        width="300px"
        :close-on-click-modal="false"
    >
      <p>确定要删除该用户吗？此操作不可撤销。</p>
      <div slot="footer">
        <el-button @click="showDeleteDialog = false">取消</el-button>
        <el-button
            type="danger"
            @click="confirmDelete"
            :loading="isDeleting"
        >
          确认删除
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import { getUserWithOrders } from '@/api/user'
import { Message, Dialog, Form, FormItem, Input, Radio, RadioGroup, Button } from "element-ui"

export default {
  name: "Home",
  components: {
    ElDialog: Dialog,
    ElForm: Form,
    ElFormItem: FormItem,
    ElInput: Input,
    ElRadio: Radio,
    ElRadioGroup: RadioGroup,
    ElButton: Button
  },
  data() {
    return {
      // 1. 用户列表数据
      userList: [],
      totalCount: 0,
      currentPage: 1,
      pageSize: 4,
      isLoading: false,

      // 2. 多表联查的用户订单列表数据
      userOrderList: [],
      orderTotalCount: 0,
      isOrderLoading: false,

      // 3. 搜索相关
      searchKeyword: '',

      // 4. 退出登录相关
      isLoggingOut: false,

      // 5. 分页跳转相关
      jumpPage: 1,

      // 6. 添加用户相关
      showAddDialog: false,
      isAdding: false,
      addForm: {
        username: '',
        phone: '',
        sex: '0',
        money: null,
        password: ''
      },
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        phone: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
        ],
        money: [
          {
            validator: (rule, value, callback) => {
              if (value === null || value === '' || value === undefined) {
                callback(new Error('请输入账户余额'));
              } else if (isNaN(Number(value))) {
                callback(new Error('请输入有效的数字'));
              } else if (Number(value) < 0) {
                callback(new Error('余额不能为负数'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ]
      },

      // 7. 删除相关
      showDeleteDialog: false,
      isDeleting: false,
      currentDeleteId: null
    };
  },
  computed: {
    totalPage() {
      return Math.ceil(this.totalCount / this.pageSize) || 1;
    },
    orderTotalPage() {
      return Math.ceil(this.orderTotalCount / this.pageSize) || 1;
    }
  },
  watch: {
    totalPage(newVal) {
      if (this.currentPage > newVal && newVal > 0) {
        this.currentPage = newVal;
      }
    },
    currentPage(newVal) {
      this.jumpPage = newVal;
    }
  },
  mounted() {
    this.getUserList();
    this.getUserOrderList();
  },
  methods: {
    // 获取普通用户列表
    getUserList() {
      this.isLoading = true;
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.searchKeyword.trim()
      };
      request({
        url: '/user/list',
        method: 'get',
        params
      }).then(res => {
        this.isLoading = false;
        if (res.code === 200 && res.data) {
          this.userList = res.data.list || [];
          this.totalCount = res.data.total || 0;
        } else {
          Message.error(res.msg || '获取用户数据失败');
        }
      }).catch(err => {
        this.isLoading = false;
        console.error('获取用户数据失败：', err);
        if (err.response && err.response.data && err.response.data.code === 401) {
          Message.error('登录已过期，请重新登录');
          this.handleLogout();
        } else {
          Message.error('加载用户列表失败，请稍后重试');
        }
      });
    },

    // 获取用户订单联查列表
    getUserOrderList() {
      this.isOrderLoading = true;
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.searchKeyword.trim()
      };
      getUserWithOrders(params).then(res => {
        this.isOrderLoading = false;
        if (res.code === 200) {
          this.userOrderList = res.data.list || [];
          this.orderTotalCount = res.data.total || 0;
        } else {
          Message.error(res.msg || '获取用户订单数据失败');
        }
      }).catch(err => {
        this.isOrderLoading = false;
        console.error('获取用户订单失败：', err);
        Message.error('加载用户订单失败，请重试');
      });
    },

    // 搜索功能
    handleSearch() {
      this.currentPage = 1;
      this.getUserList();
      this.getUserOrderList();
    },

    // 重置搜索
    resetSearch() {
      this.searchKeyword = '';
      this.currentPage = 1;
      this.getUserList();
      this.getUserOrderList();
    },

    // 切换页码
    changePage(page) {
      if (page < 1 || page > this.totalPage) return;
      this.currentPage = page;
      this.getUserList();
      this.getUserOrderList();
    },

    // 处理每页条数变化
    handlePageSizeChange() {
      this.currentPage = 1;
      this.getUserList();
      this.getUserOrderList();
    },

    // 处理页码跳转
    handleJump() {
      if (isNaN(this.jumpPage) || this.jumpPage < 1 || this.jumpPage > this.totalPage) {
        Message.warning('请输入有效的页码');
        return;
      }
      this.changePage(this.jumpPage);
    },

    // 退出登录
    handleLogout() {
      this.isLoggingOut = true;
      setTimeout(() => {
        try {
          this.$store.commit('CLEAR_USER_INFO');
          localStorage.removeItem('savedUsername');
          this.$router.push('/login');
          Message.success('已成功退出登录');
        } catch (err) {
          console.error('退出登录失败：', err);
          Message.error('退出登录失败，请重试');
        } finally {
          this.isLoggingOut = false;
        }
      }, 500);
    },

    // 时间格式化
    formatTime(time) {
      if (!time) return '无';
      const date = new Date(time);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hour = String(date.getHours()).padStart(2, '0');
      const minute = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hour}:${minute}`;
    },

    // 处理添加用户
    handleAddUser() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          this.isAdding = true;
          request({
            url: '/user/add',
            method: 'post',
            data: this.addForm
          }).then(res => {
            this.isAdding = false;
            if (res.code === 200) {
              Message.success('用户添加成功');
              this.showAddDialog = false;
              this.$refs.addForm.resetFields();
              this.currentPage = 1;
              this.getUserList();
              this.getUserOrderList();
            } else {
              Message.error(res.msg || '添加用户失败');
            }
          }).catch(err => {
            this.isAdding = false;
            console.error('添加用户失败：', err);
            Message.error('添加用户失败，请稍后重试');
          });
        }
      });
    },

    // 处理删除用户
    handleDelete(id) {
      this.currentDeleteId = id;
      this.showDeleteDialog = true;
    },

    // 确认删除
    confirmDelete() {
      if (!this.currentDeleteId) return;
      this.isDeleting = true;
      request({
        url: `/user/delete/${this.currentDeleteId}`,
        method: 'delete'
      }).then(res => {
        this.isDeleting = false;
        this.showDeleteDialog = false;
        if (res.code === 200) {
          Message.success('用户删除成功');
          if (this.userList.length === 1 && this.currentPage > 1) {
            this.currentPage--;
          }
          this.getUserList();
          this.getUserOrderList();
        } else {
          Message.error(res.msg || '删除用户失败');
        }
      }).catch(err => {
        this.isDeleting = false;
        this.showDeleteDialog = false;
        console.error('删除用户失败：', err);
        Message.error('删除用户失败，请稍后重试');
      });
    }
  }
};
</script>

<style scoped>
/* 基础样式 */
.user-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  background-color: #fff;
  min-height: 100vh;
  box-sizing: border-box;
}

/* 区块标题 */
.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 30px 0 15px;
  padding-bottom: 8px;
  border-bottom: 2px solid #667eea;
}

/* 顶部信息栏 */
.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.welcome-text {
  color: #666;
  font-size: 14px;
}

.logout-btn {
  padding: 6px 12px;
  border: none;
  background-color: #f56c6c;
  color: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.logout-btn:hover {
  background-color: #e64949;
  transform: translateY(-1px);
}

.logout-btn:active {
  transform: translateY(0);
}

/* 页面标题和操作区 */
.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.page-title {
  color: #333;
  padding-bottom: 10px;
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  border-bottom: 1px solid #eee;
  flex: 1;
  min-width: 200px;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

/* 搜索框样式 */
.search-box {
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-box input {
  width: 240px;
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  outline: none;
  transition: border-color 0.2s;
}

.search-box input:focus {
  border-color: #667eea;
}

.search-btn, .reset-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.search-btn {
  background-color: #667eea;
  color: white;
}

.search-btn:hover {
  background-color: #556cd6;
}

.reset-btn {
  background-color: #f0f2f5;
  color: #666;
}

.reset-btn:hover {
  background-color: #e5e6eb;
}

/* 添加按钮样式 */
.add-btn {
  padding: 6px 12px;
  border: none;
  background-color: #42b983;
  color: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: all 0.2s;
}

.add-btn:hover {
  background-color: #359e75;
  transform: translateY(-1px);
}

.add-btn:active {
  transform: translateY(0);
}

/* 加载状态 */
.loading {
  text-align: center;
  padding: 60px 0;
  color: #666;
}

.spinner {
  width: 40px;
  height: 40px;
  margin: 0 auto 15px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 表格样式 */
.user-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
  text-align: center;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
  transition: all 0.3s;
}

.user-table:hover {
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.user-table th,
.user-table td {
  border: 1px solid #eee;
  padding: 12px 8px;
}

.user-table th {
  background-color: #f5f7fa;
  color: #666;
  font-weight: 500;
  position: relative;
}

.user-table th::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: #667eea;
  transform: scaleX(0);
  transition: transform 0.3s;
}

.user-table th:hover::after {
  transform: scaleX(1);
}

.user-row {
  transition: background-color 0.2s;
}

.user-row:hover {
  background-color: #f9fafc;
}

.no-data {
  color: #999;
  padding: 60px 0;
}

/* 性别标签样式 */
.sex-tag {
  padding: 3px 8px;
  border-radius: 12px;
  font-size: 12px;
  color: white;
}

.sex-tag.male {
  background-color: #42b983;
}

.sex-tag.female {
  background-color: #667eea;
}

.sex-tag.unknown {
  background-color: #999;
}

/* 操作按钮样式 */
.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.delete-btn {
  padding: 4px 8px;
  border: none;
  background-color: #f56c6c;
  color: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  display: flex;
  align-items: center;
  gap: 4px;
  transition: all 0.2s;
}

.delete-btn:hover:not(:disabled) {
  background-color: #e64949;
}

.delete-btn:disabled {
  background-color: #f7b1b1;
  cursor: not-allowed;
}

/* 订单详情样式 */
.order-item {
  padding: 3px 0;
  border-bottom: 1px dashed #eee;
  font-size: 13px;
}

.order-item:last-child {
  border-bottom: none;
}

.no-order {
  color: #999;
  font-size: 13px;
}

/* 分页样式 */
.pagination {
  display: flex;
  align-items: center;
  gap: 20px;
  color: #666;
  flex-wrap: wrap;
  justify-content: center;
  padding: 10px 0;
}

.page-btn {
  padding: 5px 12px;
  border: 1px solid #ddd;
  background: #fff;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.2s;
}

.page-btn:hover:not(:disabled) {
  border-color: #667eea;
  color: #667eea;
}

.page-btn:disabled {
  color: #ccc;
  cursor: not-allowed;
  background: #fafafa;
}

.page-size select {
  padding: 5px;
  border: 1px solid #ddd;
  border-radius: 4px;
  outline: none;
  transition: border-color 0.2s;
}

.page-size select:focus {
  border-color: #667eea;
}

/* 页码导航和跳转 */
.page-navigation {
  display: flex;
  align-items: center;
  gap: 15px;
}

.page-info {
  font-size: 14px;
}

.page-jump {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.page-jump input {
  width: 50px;
  padding: 3px 5px;
  border: 1px solid #ddd;
  border-radius: 4px;
  text-align: center;
  outline: none;
  transition: border-color 0.2s;
}

.page-jump input:focus {
  border-color: #667eea;
}

.jump-btn {
  padding: 3px 8px;
  border: 1px solid #ddd;
  background: #fff;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.2s;
  font-size: 13px;
}

.jump-btn:hover {
  border-color: #667eea;
  color: #667eea;
}

/* 适配小屏幕 */
@media (max-width: 768px) {
  .search-box input {
    width: 160px;
  }

  .header-actions {
    flex-direction: column;
    align-items: flex-start;
  }

  .pagination {
    gap: 10px;
  }

  .page-navigation {
    flex-direction: column;
    gap: 8px;
  }
}
</style>
